package com.vlyman.utils;

/**
 * 类描述：
 *  字节操作工具类
 * @author chenjs
 * @date 2019/1/14 17:29
 **/
public class ByteUtil {

    /**
     * 方法描述：
     *   java字节码转字符串
     *  @author chenjs
     *  @param bytes
     *  @return String
     *  @date 2019/1/12 14:28
     */
    public static String byte2hex(byte[] bytes) {
        //一个字节的数，转成16进制字符串
        StringBuffer hs = new StringBuffer();
        String tmp;
        for (byte byteItem : bytes) {
            //整数转成十六进制表示
            tmp = (Integer.toHexString(byteItem & 0XFF));
            if (tmp.length() == 1) {
                hs.append("0");
                hs.append(tmp);
            } else {
                hs.append(tmp);
            }
        }
        return hs.toString();
    }

    public static String toHexString(String s) {
        StringBuffer strSb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            strSb.append(Integer.toHexString(ch));
        }
        return strSb.toString();
    }

    /**
     * 方法描述：
     *   16进制字符串改为byte[]
     *  @author chenjs
     *  @param hexString
     *  @return byte[]
     *  @date 2019/1/12 14:31
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || "".equals(hexString)) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * 方法描述：
     *   将char转为byte
     *  @author chenjs
     *  @param c
     *  @return byte
     *  @date 2019/1/12 14:30
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}
